"""
# -*- coding: utf-8 -*-
# @Time : 2023/4/22 17:36
# @Author : LTY
# @File : L231_PP_PictureFunction_Page_test.py
# @function : python3.9.2
"""

import sys
import time
import serial
import serial.tools.list_ports
import binascii
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QRegExpValidator, QIntValidator, QPixmap, QIcon
from PyQt5.QtCore import QRegExp            # QT里面正则表达式的类
from PyQt5.QtCore import Qt, QTimer

from ui_QT.ui_PictureFunctionPage import Ui_MainWindow as PictureFunc_ui_Main
from L231_PP_RSB4BQTtest_LTY_230414 import L231_PP_Main_Page_test as Main_Func

Serial_code_type1_item = ''
Serial_code_type1 = ''
Serial_code_type2 = b''
receive_code_type1_item = ''
receive_code_type1 = ''
receive_code_type2 = b''


class QT_PictureFunction(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)  # 调用父类构造函数，创建窗体
        self.ui_Func = PictureFunc_ui_Main()  # 创建UI对象
        self.ui_Func.setupUi(self)  # 构造UI界面
        self.ser = serial.Serial()
        self.textEdit = self.ui_Func.textEdit
        self.label = self.ui_Func.label_8
        self.timer = QTimer(self)
        self.cap_data = []
        self.initUI()
        self.center()
        self.Serial_code_type1 = ''
        self.Serial_code_type2 = b''
        self.receive_code_type1 = ''
        self.receive_code_type2 = b''

        # 接收数据和发送数据数目置零
        self.data_num_received = 0
        self.data_num_sended = 0

##  ==============自定义功能函数========================
    def initUI(self):
        self.setWindowTitle('图像采集页面')

        # 按钮设置
        self.button_return = self.ui_Func.pushButton_return
        self.button_return.clicked.connect(self.RETURN)
        self.button_return.setShortcut("Esc")
        self.button_send_single = self.ui_Func.pushButton_send_single
        self.button_send_single.clicked.connect(self.SEND_SINGLE)
        self.button_send_multi = self.ui_Func.pushButton_send_multi
        self.button_send_multi.clicked.connect(self.SEND_MULTI)
        self.button_send_halt = self.ui_Func.pushButton_send_halt
        self.button_send_halt.clicked.connect(self.SEND_HALT)

        self.button_select_1 = self.ui_Func.radioButton
        self.button_select_1.setChecked(False)
        self.button_select_1.toggled.connect(self.buttonState)
        self.button_select_2 = self.ui_Func.radioButton_2
        self.button_select_2.setChecked(False)
        self.button_select_2.toggled.connect(self.buttonState)

        # 平皿ID
        DishID = self.ui_Func.lineEdit_DishID
        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        DishID.setValidator(validator)

        DishID.setPlaceholderText('十八位整数')

        # 灯光模式
        LgtMod = self.ui_Func.lineEdit_LgtMod
        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        LgtMod.setValidator(validator)

        intValidator = QIntValidator(self)
        intValidator.setRange(0, 9)
        LgtMod.setValidator(intValidator)

        # 相机模式
        CamMod = self.ui_Func.lineEdit_CamMod
        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        CamMod.setValidator(validator)

        intValidator = QIntValidator(self)
        intValidator.setRange(0, 9)
        CamMod.setValidator(intValidator)

        # 白平衡（白）
        WbWhit = self.ui_Func.lineEdit_WbWhit
        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        WbWhit.setValidator(validator)

        intValidator = QIntValidator(self)
        intValidator.setRange(1, 8)
        WbWhit.setValidator(intValidator)

        # 白平衡（蓝）
        WbBlue = self.ui_Func.lineEdit_WbBlue
        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        WbBlue.setValidator(validator)

        intValidator = QIntValidator(self)
        intValidator.setRange(1, 8)
        WbBlue.setValidator(intValidator)

        # 温度（摄氏度）
        CenTem = self.ui_Func.lineEdit_CenTem
        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        CenTem.setValidator(validator)

        CenTem.setPlaceholderText('三个整数')
        Validator = QRegExpValidator(self)
        Validator.setRegExp(reg)
        CenTem.setValidator(Validator)

        # 湿度
        RelHum = self.ui_Func.lineEdit_RelHum
        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        RelHum.setValidator(validator)

        RelHum.setPlaceholderText('三个整数')
        Validator = QRegExpValidator(self)
        Validator.setRegExp(reg)
        RelHum.setValidator(Validator)

        # 实际拍照时间
        address = r"C:\Users\lclvlb\Desktop\L231项目周计划与周报\L231code\bisheQT\temp.txt"
        with open(address, 'r') as f:
            PicTim_data = f.read()
        PicTim_year = PicTim_data[0] + PicTim_data[1]
        PicTim_month = PicTim_data[2] + PicTim_data[3]
        PicTim_date = PicTim_data[4] + PicTim_data[5]
        PicTim_hour = PicTim_data[6] + PicTim_data[7]
        PicTim_minute = PicTim_data[8] + PicTim_data[9]
        PicTim_second = PicTim_data[10] + PicTim_data[11]
        self.ui_Func.lineEdit_PicTim_year.setText(PicTim_year)
        self.ui_Func.lineEdit_PicTim_month.setText(PicTim_month)
        self.ui_Func.lineEdit_PicTim_date.setText(PicTim_date)
        self.ui_Func.lineEdit_PicTim_hour.setText(PicTim_hour)
        self.ui_Func.lineEdit_PicTim_minute.setText(PicTim_minute)
        self.ui_Func.lineEdit_PicTim_second.setText(PicTim_second)

        # 拍照间隔
        Interval_hour = self.ui_Func.lineEdit_Interval_hour.text()
        Interval_minute = self.ui_Func.lineEdit_Interval_minute.text()
        Interval_second = self.ui_Func.lineEdit_Interval_second.text()

    def center(self):
        # 获取屏幕坐标系
        screen = QDesktopWidget().screenGeometry()
        # print(screen.width(), screen.height())
        # 获取窗口坐标系
        size = self.geometry()
        # print(size.width(), size.height())
        # 移动窗口至屏幕中央
        newLeft = (screen.width() - size.width()) / 2
        newTop = (screen.height() - size.height()) / 2
        self.move(int(newLeft), int(newTop))

    def RETURN(self):
        text = self.sender().text()
        if text == "返回":
            reply = QMessageBox.question(self, 'Return', '您是否要返回', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            if reply == QMessageBox.Yes:
                self.ui_Begin = Main_Func.QT_Function()
                self.close()
                self.ui_Begin.show()

    # 打开串口
    def port_open(self):
        self.ser.port = 'COM3'
        self.ser.baudrate = 9600
        self.ser.bytesize = 8
        self.ser.stopbits = 1

        try:
            self.ser.open()
        except:
            QMessageBox.critical(self, "Port Error", "此串口不能被打开！")
            return None

    # 关闭串口
    def port_close(self):
        try:
            self.ser.close()
        except:
            # 接收数据和发送数据数目置零
            self.data_num_received = 0
            self.data_num_sended = 0

    def calc(self):
        DishID = self.ui_Func.lineEdit_DishID.text()
        LgtMod = self.ui_Func.lineEdit_LgtMod.text()
        CamMod = self.ui_Func.lineEdit_CamMod.text()
        WbWhit = self.ui_Func.lineEdit_WbWhit.text()
        WbBlue = self.ui_Func.lineEdit_WbBlue.text()
        CenTem = self.ui_Func.lineEdit_CenTem.text()
        RelHum = self.ui_Func.lineEdit_RelHum.text()

        PicTim_year = self.ui_Func.lineEdit_PicTim_year.text()
        PicTim_month = self.ui_Func.lineEdit_PicTim_month.text()
        PicTim_date = self.ui_Func.lineEdit_PicTim_date.text()
        PicTim_hour = self.ui_Func.lineEdit_PicTim_hour.text()
        PicTim_minute = self.ui_Func.lineEdit_PicTim_minute.text()
        PicTim_second = self.ui_Func.lineEdit_PicTim_second.text()

        if self.ui_Func.lineEdit_DishID.text() == '' or self.ui_Func.lineEdit_LgtMod.text() == '' \
                or self.ui_Func.lineEdit_CamMod.text() == '' or self.ui_Func.lineEdit_WbWhit.text() == '' \
                or self.ui_Func.lineEdit_WbBlue.text() == '' or self.ui_Func.lineEdit_CenTem.text() == '' \
                or self.ui_Func.lineEdit_RelHum.text() == '' or self.ui_Func.lineEdit_PicTim_year.text() == '' \
                or self.ui_Func.lineEdit_PicTim_month.text() == '' or self.ui_Func.lineEdit_PicTim_date.text() == '' \
                or self.ui_Func.lineEdit_PicTim_hour.text() == '' or self.ui_Func.lineEdit_PicTim_minute.text() == '' \
                or self.ui_Func.lineEdit_PicTim_second.text() == '':

            UNCOMPLETE_ANSWER = 'CONTINUE_INPUT'
            return UNCOMPLETE_ANSWER

        else:
            global Serial_code_type1_item
            global Serial_code_type1
            global Serial_code_type2

            Serial_code_type1_list = [b'~', b'6', b'4', b'40']
            Serial_code_type2 = b'\x7e\x06\x04\x28'
            Items = []

            DishID_list = []
            for i in range(0, len(DishID)):
                DishID_item = (ord(str(int(DishID[i])))).to_bytes(1, 'big')
                DishID_list.append(DishID_item)
            Items = Items + DishID_list

            LgtMod_item = (ord(str(LgtMod))).to_bytes(1, 'big')
            Items.append(LgtMod_item)

            CamMod_item = (ord(str(CamMod))).to_bytes(1, 'big')
            Items.append(CamMod_item)

            WbWhit_item = (ord(str(WbWhit))).to_bytes(1, 'big')
            Items.append(WbWhit_item)

            WbBlue_item = (ord(str(WbBlue))).to_bytes(1, 'big')
            Items.append(WbBlue_item)

            CenTem_list = []
            for i in range(0, len(CenTem)):
                CenTem_item = (ord(str(int(CenTem[i])))).to_bytes(1, 'big')
                CenTem_list.append(CenTem_item)
            # print(DishID_list)
            Items = Items + CenTem_list

            RelHum_list = []
            for i in range(0, len(RelHum)):
                RelHum_item = (ord(str(int(RelHum[i])))).to_bytes(1, 'big')
                RelHum_list.append(RelHum_item)
            # print(DishID_list)
            Items = Items + RelHum_list

            PicTim_year_tens = (ord(str(int(int(PicTim_year) / 10)))).to_bytes(1, 'big')
            PicTim_year_unit = (ord(str(int(int(PicTim_year) % 10)))).to_bytes(1, 'big')
            PicTim_month_tens = (ord(str(int(int(PicTim_month) / 10)))).to_bytes(1, 'big')
            PicTim_month_unit = (ord(str(int(int(PicTim_month) % 10)))).to_bytes(1, 'big')
            PicTim_date_tens = (ord(str(int(int(PicTim_date) / 10)))).to_bytes(1, 'big')
            PicTim_date_unit = (ord(str(int(int(PicTim_date) % 10)))).to_bytes(1, 'big')
            PicTim_hour_tens = (ord(str(int(int(PicTim_hour) / 10)))).to_bytes(1, 'big')
            PicTim_hour_unit = (ord(str(int(int(PicTim_hour) % 10)))).to_bytes(1, 'big')
            PicTim_minute_tens = (ord(str(int(int(PicTim_minute) / 10)))).to_bytes(1, 'big')
            PicTim_minute_unit = (ord(str(int(int(PicTim_minute) % 10)))).to_bytes(1, 'big')
            PicTim_second_tens = (ord(str(int(int(PicTim_second) / 10)))).to_bytes(1, 'big')
            PicTim_second_unit = (ord(str(int(int(PicTim_second) % 10)))).to_bytes(1, 'big')
            PicTim_data_list = [PicTim_year_tens, PicTim_year_unit, PicTim_month_tens, PicTim_month_unit,
                                PicTim_date_tens, PicTim_date_unit, PicTim_hour_tens, PicTim_hour_unit,
                                PicTim_minute_tens, PicTim_minute_unit, PicTim_second_tens, PicTim_second_unit]
            Items.extend(PicTim_data_list)

            pre_check_code = 50
            for i in range(0, len(Items)):
                pre_check_code += int(binascii.b2a_hex(Items[i]), base=16)
            check_code = pre_check_code & 0xFF  # 取低八位
            byte_check_code = check_code.to_bytes(1, 'big')

            Items.append(byte_check_code)
            Items.append(b'\xe7')

            Serial_code_type1_list.extend(Items)
            for item in Serial_code_type1_list:
                item = hex(int.from_bytes(item, byteorder='big'))
                Serial_code_type1_item = Serial_code_type1_item + '\\' + str(item)
            Serial_code_type1 = Serial_code_type1_item
            self.Serial_code_type1 = Serial_code_type1
            Serial_code_type1_item = ''
            print("Serial_code_type1 =", self.Serial_code_type1)
            # self.ui_Func.textEdit_send_commod.setText(str(Serial_code_type1))

            for i in range(0, len(Items)):
                Serial_code_type2 += Items[i]
                self.Serial_code_type2 = Serial_code_type2
            print("Serial_code_type2 =", self.Serial_code_type2)
            # self.ui_Func.textEdit_send_commod.setText(str(Serial_code))

            return Serial_code_type2

    def Textviewer(self, file_create_time):
        DishID = self.ui_Func.lineEdit_DishID.text()
        # 自定义格式
        address = r"C:\Users\lclvlb\Desktop\L231项目周计划与周报\L231code\bisheQT\FILE.txt"
        with open(address, 'r') as f:
            file_path = f.read()

        file_name = "\\PictureMessage_DishID" + DishID + "_TIME" + file_create_time + ".txt"
        address = "Z:\Exp_File\exp" +"\\" + file_path + "\DishID" + DishID + file_name
        print(address)

        with open(address, 'r') as f:
            if f:
                my_file = f.read()
                self.textEdit.setText(my_file)
            else:
                dialog = QDialog()
                dialog.resize(230, 80)
                label1 = QLabel(dialog)
                label1.setText("未找到指定文件")
                label1.move(65, 10)
                button = QPushButton('确定', dialog)
                button.clicked.connect(dialog.close)
                button.move(70, 40)
                dialog.setWindowTitle('无法打开文件')
                dialog.setWindowModality(Qt.ApplicationModal)  # 防止子窗口响应后，主串口继续相应
                dialog.exec()

    def Pictureviewer(self):
        DishID = self.ui_Func.lineEdit_DishID.text()
        LgtMod = self.ui_Func.lineEdit_LgtMod.text()
        CamMod = self.ui_Func.lineEdit_CamMod.text()
        WbWhit = self.ui_Func.lineEdit_WbWhit.text()
        WbBlue = self.ui_Func.lineEdit_WbBlue.text()
        CenTem = self.ui_Func.lineEdit_CenTem.text()
        RelHum = self.ui_Func.lineEdit_RelHum.text()

        PicTim_year = self.ui_Func.lineEdit_PicTim_year.text()
        PicTim_month = self.ui_Func.lineEdit_PicTim_month.text()
        PicTim_date = self.ui_Func.lineEdit_PicTim_date.text()
        PicTim_hour = self.ui_Func.lineEdit_PicTim_hour.text()
        PicTim_minute = self.ui_Func.lineEdit_PicTim_minute.text()
        PicTim_second = self.ui_Func.lineEdit_PicTim_second.text()
        PicTim = PicTim_year + PicTim_month + PicTim_date + PicTim_hour + PicTim_minute + PicTim_second

        # DishID010100102303082424_LM2_CM1_WBW7_WBB5_TMP362_HUM520_PicTim230308143750.jpg
        address = r"C:\Users\lclvlb\Desktop\L231项目周计划与周报\L231code\bisheQT\FILE.txt"
        with open(address, 'r') as f:
            if f:
                file_path = f.read()
            else:
                dialog = QDialog()
                dialog.resize(230, 80)
                label1 = QLabel(dialog)
                label1.setText("未找到指定实验命名文件")
                label1.move(55, 10)
                button = QPushButton('确定', dialog)
                button.clicked.connect(dialog.close)
                button.move(70, 40)
                dialog.setWindowTitle('无法打开文件')
                dialog.setWindowModality(Qt.ApplicationModal)  # 防止子窗口响应后，主串口继续相应
                dialog.exec()

        header = "Z:\Exp_File\img\exp" + '\\' + file_path
        PictureFile_name = "\DishID" + DishID + "_LM" + LgtMod + "_CM" + CamMod + \
                           "_WBW" + WbWhit + "_WBB" + WbBlue + \
                           "_TMP" + CenTem + "_HUM" + RelHum + "_PicTim" + PicTim + ".jpg"

        my_pic_path = header + PictureFile_name
        print(my_pic_path)
        pix = QPixmap(my_pic_path)
        self.label.setPixmap(pix)
        self.label.setScaledContents(True)  # 自适应QLabel大小

    def time_start(self, Interval_time):
        self.timer.start(Interval_time)

    def SEND_SINGLE(self):
        INPUT_ANSWER = self.calc()
        if INPUT_ANSWER == 'CONTINUE_INPUT':
            dialog = QDialog()
            dialog.resize(230, 80)
            label1 = QLabel(dialog)
            label1.setText("请输入完整信息")
            label1.move(65, 10)
            button = QPushButton('继续输入', dialog)
            button.clicked.connect(dialog.close)
            button.move(70, 40)
            dialog.setWindowTitle('信息不全')
            dialog.setWindowModality(Qt.ApplicationModal)  # 防止子窗口响应后，主串口继续相应
            dialog.exec()
        else:
            try:
                self.port_open()
                # self.ser.flushInput()  # 清空输入缓冲区
                if self.ser.isOpen():
                    self.ser.write(INPUT_ANSWER)

                    frame_header_chack = self.ser.read()
                    if frame_header_chack == b'\x7e':
                        self.cap_data.append(frame_header_chack)
                        for i in range(1, 100):
                            uart_data = self.ser.read()
                            self.cap_data.append(uart_data)

                            # 查询帧尾
                            if self.cap_data[i] == b'\xe7':
                                break

                    # print(self.cap_data)
                    global receive_code_type1_item
                    global receive_code_type1
                    global receive_code_type2

                    receive_code_type2 = b'\x7e\x06\x06'

                    for item in self.cap_data:
                        item = hex(int.from_bytes(item, byteorder='big'))
                        receive_code_type1_item = receive_code_type1_item + '\\' + str(item)
                    receive_code_type1 = receive_code_type1_item
                    self.receive_code_type1 = receive_code_type1
                    receive_code_type1_item = ''
                    # self.ui_Func.textEdit_receive_commod.setText(receive_code_type1)
                    print('receive_code_type1 = ', self.receive_code_type1)

                    for i in range(3, len(self.cap_data)):
                        receive_code_type2 += self.cap_data[i]
                        self.receive_code_type2 = receive_code_type2
                    print("receive_code_type2 = ", self.receive_code_type2)

                    year = chr(int.from_bytes(self.cap_data[4], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[5], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[6], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[7], byteorder='big'))
                    month = chr(int.from_bytes(self.cap_data[8], byteorder='big')) + \
                            chr(int.from_bytes(self.cap_data[9], byteorder='big'))
                    date = chr(int.from_bytes(self.cap_data[10], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[11], byteorder='big'))
                    hour = chr(int.from_bytes(self.cap_data[12], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[13], byteorder='big'))
                    minute = chr(int.from_bytes(self.cap_data[14], byteorder='big')) + \
                             chr(int.from_bytes(self.cap_data[15], byteorder='big'))
                    second = chr(int.from_bytes(self.cap_data[16], byteorder='big')) + \
                             chr(int.from_bytes(self.cap_data[17], byteorder='big'))
                    file_create_time = year + month + date + hour + minute + second
                    # print(file_create_time)
                    self.port_close()
                    self.cap_data.clear()
                    self.Textviewer(file_create_time)
                    self.Pictureviewer()

                else:
                    self.port_close()
                    QMessageBox.critical(self, "Port Error", "传输失败")

            except KeyboardInterrupt:
                self.port_close()

    def CLEAR_INTERVAL_TIME(self):
        self.ui_Func.lineEdit_Interval_hour.clear()
        self.ui_Func.lineEdit_Interval_minute.clear()
        self.ui_Func.lineEdit_Interval_second.clear()

    def Interval_time_calc(self):
        # print(self.ui_Func.lineEdit_Interval_second.text() == '')
        if self.ui_Func.lineEdit_Interval_hour.text() == '' or self.ui_Func.lineEdit_Interval_minute.text() == '' \
                or self.ui_Func.lineEdit_Interval_second.text() == '':
            dialog = QDialog()
            dialog.resize(230, 80)
            label1 = QLabel(dialog)
            label1.setText("请补充完整信息")
            label1.move(65, 10)
            button = QPushButton('确定', dialog)
            button.clicked.connect(dialog.close)
            button.clicked.connect(self.CLEAR_INTERVAL_TIME)
            button.move(70, 40)
            dialog.setWindowTitle('信息不完整')
            dialog.setWindowModality(Qt.ApplicationModal)  # 防止子窗口响应后，主串口继续相应
            dialog.exec()
            return 0

        else:
            Interval_hour = self.ui_Func.lineEdit_Interval_hour.text()
            Interval_minute = self.ui_Func.lineEdit_Interval_minute.text()
            Interval_second = self.ui_Func.lineEdit_Interval_second.text()
            Interval_time = (int(Interval_hour) * 3600 + int(Interval_minute) * 60 + int(Interval_second)) * 1000
            # print(Interval_time)

            return Interval_time

    def NextPicTime_calc(self):
        # 下次拍照时间
        NextPictime_second = int(self.ui_Func.lineEdit_PicTim_second.text()) + \
                             int(self.ui_Func.lineEdit_Interval_second.text())
        NextPictime_minute = int(self.ui_Func.lineEdit_PicTim_minute.text()) + \
                             int(self.ui_Func.lineEdit_Interval_minute.text())
        NextPictime_hour = int(self.ui_Func.lineEdit_PicTim_hour.text()) + \
                           int(self.ui_Func.lineEdit_Interval_hour.text())
        NextPictime_date = int(self.ui_Func.lineEdit_PicTim_date.text())
        NextPictime_month = int(self.ui_Func.lineEdit_PicTim_month.text())
        NextPictime_year = int(self.ui_Func.lineEdit_PicTim_year.text())

        if NextPictime_second >= 60:
            NextPictime_second = NextPictime_second - 60
            NextPictime_minute += 1
            if NextPictime_minute >= 60:
                NextPictime_minute = NextPictime_minute - 60
                NextPictime_hour += 1
                if NextPictime_hour >= 24:
                    NextPictime_hour = NextPictime_hour - 24
                    NextPictime_date += 1
                    if NextPictime_month == 1 and NextPictime_date > 31:
                        NextPictime_date = NextPictime_date - 31
                        NextPictime_month = 2
                    if NextPictime_month == 3 and NextPictime_date > 31:
                        NextPictime_date = NextPictime_date - 31
                        NextPictime_month = 4
                    if NextPictime_month == 4 and NextPictime_date > 30:
                        NextPictime_date = NextPictime_date - 30
                        NextPictime_month = 5
                    if NextPictime_month == 5 and NextPictime_date > 31:
                        NextPictime_date = NextPictime_date - 31
                        NextPictime_month = 6
                    if NextPictime_month == 6 and NextPictime_date > 30:
                        NextPictime_date = NextPictime_date - 30
                        NextPictime_month = 7
                    if NextPictime_month == 7 and NextPictime_date > 31:
                        NextPictime_date = NextPictime_date - 31
                        NextPictime_month = 8
                    if NextPictime_month == 8 and NextPictime_date > 31:
                        NextPictime_date = NextPictime_date - 31
                        NextPictime_month = 9
                    if NextPictime_month == 9 and NextPictime_date > 30:
                        NextPictime_date = NextPictime_date - 30
                        NextPictime_month = 10
                    if NextPictime_month == 10 and NextPictime_date > 31:
                        NextPictime_date = NextPictime_date - 31
                        NextPictime_month = 11
                    if NextPictime_month == 11 and NextPictime_date > 31:
                        NextPictime_date = NextPictime_date - 31
                        NextPictime_month = 12
                    if NextPictime_month == 12 and NextPictime_date > 30:
                        NextPictime_date = NextPictime_date - 30
                        NextPictime_month = 1
                        NextPictime_year = NextPictime_year + 1

                    if ((NextPictime_year + 2000) % 4 == 0 and (NextPictime_year + 2000) % 100 != 0) \
                            or (NextPictime_year + 2000) % 400 == 0:
                        if NextPictime_month == 2 and NextPictime_date > 29:
                            NextPictime_date = NextPictime_date - 29
                            NextPictime_month = 3
                    else:
                        if NextPictime_month == 2 and NextPictime_date > 28:
                            NextPictime_date = NextPictime_date - 28
                            NextPictime_month = 3

        self.ui_Func.lineEdit_NextPicTim_year.setText("{:0>2d}".format(NextPictime_year))
        self.ui_Func.lineEdit_NextPicTim_month.setText("{:0>2d}".format(NextPictime_month))
        self.ui_Func.lineEdit_NextPicTim_date.setText("{:0>2d}".format(NextPictime_date))
        self.ui_Func.lineEdit_NextPicTim_hour.setText("{:0>2d}".format(NextPictime_hour))
        self.ui_Func.lineEdit_NextPicTim_minute.setText("{:0>2d}".format(NextPictime_minute))
        self.ui_Func.lineEdit_NextPicTim_second.setText("{:0>2d}".format(NextPictime_second))

        INPUT_ANSWER = self.calc()
        if INPUT_ANSWER == 'CONTINUE_INPUT':
            dialog = QDialog()
            dialog.resize(230, 80)
            label1 = QLabel(dialog)
            label1.setText("请输入完整信息")
            label1.move(65, 10)
            button = QPushButton('继续输入', dialog)
            button.clicked.connect(dialog.close)
            button.move(70, 40)
            dialog.setWindowTitle('信息不全')
            dialog.setWindowModality(Qt.ApplicationModal)  # 防止子窗口响应后，主串口继续相应
            dialog.exec()
        else:
            try:
                self.port_open()
                # self.ser.flushInput()  # 清空输入缓冲区
                if self.ser.isOpen():
                    self.ser.write(INPUT_ANSWER)
                    frame_header_chack = self.ser.read()
                    if frame_header_chack == b'\x7e':
                        self.cap_data.append(frame_header_chack)
                        for i in range(1, 100):
                            uart_data = self.ser.read()
                            self.cap_data.append(uart_data)

                            # 查询帧尾
                            if self.cap_data[i] == b'\xe7':
                                break

                    # print(self.cap_data)
                    global receive_code_type1_item
                    global receive_code_type2
                    receive_code_type2 = b'\x7e\x06\x06'

                    for item in self.cap_data:
                        item = hex(int.from_bytes(item, byteorder='big'))
                        receive_code_type1_item = receive_code_type1_item + '\\' + str(item)
                    # self.ui_Func.textEdit_receive_commod.setText(receive_code_type1)
                    self.receive_code_type1 = receive_code_type1_item
                    print('s1 = ', self.receive_code_type1)

                    for i in range(3, len(self.cap_data)):
                        receive_code_type2 += self.cap_data[i]
                    print("s2 =", receive_code_type2)

                    year = chr(int.from_bytes(self.cap_data[4], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[5], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[6], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[7], byteorder='big'))
                    month = chr(int.from_bytes(self.cap_data[8], byteorder='big')) + \
                            chr(int.from_bytes(self.cap_data[9], byteorder='big'))
                    date = chr(int.from_bytes(self.cap_data[10], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[11], byteorder='big'))
                    hour = chr(int.from_bytes(self.cap_data[12], byteorder='big')) + \
                           chr(int.from_bytes(self.cap_data[13], byteorder='big'))
                    minute = chr(int.from_bytes(self.cap_data[14], byteorder='big')) + \
                             chr(int.from_bytes(self.cap_data[15], byteorder='big'))
                    second = chr(int.from_bytes(self.cap_data[16], byteorder='big')) + \
                             chr(int.from_bytes(self.cap_data[17], byteorder='big'))
                    file_create_time = year + month + date + hour + minute + second
                    # print(file_create_time)
                    self.cap_data.clear()
                    self.port_close()
                    self.Textviewer(file_create_time)
                    self.Pictureviewer()

                else:
                    self.port_close()
                    QMessageBox.critical(self, "Port Error", "传输失败")

            except KeyboardInterrupt:
                self.port_close()

    def Twice_NextPicTime_calc(self):
        self.ui_Func.lineEdit_PicTim_year.setText(self.ui_Func.lineEdit_NextPicTim_year.text())
        self.ui_Func.lineEdit_PicTim_month.setText(self.ui_Func.lineEdit_NextPicTim_month.text())
        self.ui_Func.lineEdit_PicTim_date.setText(self.ui_Func.lineEdit_NextPicTim_date.text())
        self.ui_Func.lineEdit_PicTim_hour.setText(self.ui_Func.lineEdit_NextPicTim_hour.text())
        self.ui_Func.lineEdit_PicTim_minute.setText(self.ui_Func.lineEdit_NextPicTim_minute.text())
        self.ui_Func.lineEdit_PicTim_second.setText(self.ui_Func.lineEdit_NextPicTim_second.text())

        self.ui_Func.lineEdit_NextPicTim_year.clear()
        self.ui_Func.lineEdit_NextPicTim_month.clear()
        self.ui_Func.lineEdit_NextPicTim_date.clear()
        self.ui_Func.lineEdit_NextPicTim_hour.clear()
        self.ui_Func.lineEdit_NextPicTim_minute.clear()
        self.ui_Func.lineEdit_NextPicTim_second.clear()

        self.textEdit.clear()
        self.label.clear()
        self.NextPicTime_calc()

    def SEND_MULTI(self):
        Interval_time = self.Interval_time_calc()

        if Interval_time != 0:
            self.NextPicTime_calc()
            self.time_start(Interval_time)
            self.timer.timeout.connect(self.Twice_NextPicTime_calc)

        elif Interval_time == 0:
            return 0

    def SEND_HALT(self):
        self.timer.stop()
        Serial_code = b'\x7e\x06\x04\x11'
        Items = []
        commond = b'HaltTakingPicture'
        # print(bytes(chr(commond[0]).encode('utf-8')))
        for i in range(0, len(commond)):
            Items.append(bytes(chr(commond[i]).encode('utf-8')))
        # print(Items)

        pre_check_code = 27
        for i in range(0, len(Items)):
            pre_check_code += int(binascii.b2a_hex(Items[i]), base=16)
        check_code = pre_check_code & 0xFF  # 取低八位
        byte_check_code = check_code.to_bytes(1, 'big')

        Items.append(byte_check_code)
        Items.append(b'\xe7')

        for i in range(0, len(Items)):
            Serial_code += Items[i]
        print(Serial_code)
        self.ui_Func.textEdit_send_commod.setText(str(Serial_code))

        try:
            self.port_open()
            # self.ser.flushInput()  # 清空输入缓冲区
            if self.ser.isOpen():
                self.ser.write(Serial_code)
                self.port_close()
            else:
                self.port_close()
                QMessageBox.critical(self, "Port Error", "传输失败")

        except KeyboardInterrupt:
            self.port_close()

    def button_show_Hex(self):
        self.ui_Func.textEdit_send_commod.setText(Serial_code_type1)
        self.ui_Func.textEdit_receive_commod.setText(receive_code_type1)

    def button_show_ASCII(self):
        self.ui_Func.textEdit_send_commod.setText(str(Serial_code_type2))
        self.ui_Func.textEdit_receive_commod.setText(str(receive_code_type2))

    def buttonState(self):
        radioButton = self.sender()  # 获取自身发出信号的对象
        if radioButton.text() == '显示16进制':
            if radioButton.isChecked() == True:
                self.button_show_Hex()

        if radioButton.text() == '显示ASCII码':
            if radioButton.isChecked() == True:
                self.button_show_ASCII()


##  ============窗体测试程序 ================================
if __name__ == "__main__":  # 用于当前窗体测试
    app = QApplication(sys.argv)  # 创建GUI应用程序
    app.setWindowIcon(QIcon('..\\image\\school(256).ico'))
    form = QT_PictureFunction()  # 创建窗体
    form.show()

    sys.exit(app.exec_())
